import axios from 'axios';
import React from 'react';
import { Navigate, history } from 'umi';
import Loading from './loading';

interface MenuItem {
  path?: string;
  name?: string;
  icon?: string;
  id?: number;
  children?: MenuItem[];
  is_source?: boolean;
}

interface RouteItem {
  path: string;
  name?: string;
  children?: RouteItem[];
  routes?: RouteItem[];
  element?: React.ReactElement;
  component?: string;
}

// 全局状态变量
let appState = {
  currentUser: null as any,
  menuList: [] as MenuItem[],
  dynamicRoutes: [] as any[],
  isLoaded: false, // 标记数据是否已加载
  token: '' // 当前使用的token
};

// 菜单数据删除多余字段is_source 解决控制台报错问题
const removeCustomProps = (obj: any, depth = 0): any => {
  if (depth > 10) return obj;
  
  if (typeof obj !== 'object' || obj === null) return obj;
  
  if (Array.isArray(obj)) {
    return obj.map(item => removeCustomProps(item, depth + 1));
  }
  
  const newObj: any = {};
  Object.keys(obj).forEach(key => {
    if (key === 'is_source') return;
    newObj[key] = removeCustomProps(obj[key], depth + 1);
  });
  return newObj;
};

// 递归过滤is_source为true的路由（不注册此类路由）
const filterSourceRoutes = (routes: MenuItem[]): MenuItem[] => {
  return routes.flatMap(route => {
    if (route.is_source) return [];
    
    const children = route.children 
      ? filterSourceRoutes(route.children) 
      : undefined;
      
    return children && children.length > 0 
      ? { ...route, children } 
      : { ...route, children: undefined };
  });
};

// 合并本地静态路由与动态路由
const mergeRoutes = (localRoutes: RouteItem[], dynamicRoutes: RouteItem[]): RouteItem[] => {
  const routeMap = new Map();
  
  localRoutes.forEach(route => {
    routeMap.set(route.path, route);
  });
  
  dynamicRoutes.forEach(dynamicRoute => {
    if ((dynamicRoute as any).is_source) return;
    
    const existingRoute = routeMap.get(dynamicRoute.path);
    
    if (existingRoute) {
      existingRoute.children = [
        ...(existingRoute.children || []),
        ...(dynamicRoute.children || [])
      ];
    } else {
      routeMap.set(dynamicRoute.path, dynamicRoute);
    }
  });
  
  return Array.from(routeMap.values());
};

/**
 * 加载用户状态和菜单数据（仅在应用初始化时调用）
 */
async function loadUserAndMenuState() {
  // 如果已经加载过数据，直接返回
  if (appState.isLoaded) return;
  
  const token = localStorage.getItem('token') || '';
  
  // 如果token为空，设置初始状态并返回
  if (!token) {
    appState = {
      currentUser: null,
      menuList: [],
      dynamicRoutes:[],
      isLoaded: true,
      token: ''
    };
    return;
  }
  
  // 如果token未变化，且已加载过数据，直接返回
  if (appState.token === token && appState.isLoaded) {
    return;
  }

  try {
    const [userRes, menuRes] = await Promise.all([
      axios.get('/api/user/info', { headers: { token } }),
      axios.get('/api/menuList', { headers: { token } })
    ]);

    if (userRes.data.code === 200) {
      appState.currentUser = userRes.data.data;
    }

    if (menuRes.data.code === 200) {
      const menuData = menuRes.data.data || [];
      appState.menuList = removeCustomProps(menuData);
      appState.dynamicRoutes = dealDynamicRoutes(menuData);
    }
    
    // 标记数据已加载
    appState.isLoaded = true;
    appState.token = token;
  } catch (error) {
    console.error('加载用户或菜单数据失败:', error);
    // 即使加载失败，也标记为已加载，避免重复请求
    appState = {
      currentUser: null,
      menuList: [],
      dynamicRoutes:[],
      isLoaded: true,
      token
    };
  }
}

/**
 * 封装处理为umi 可识别的路由信息 动态导入组件
 * @param routes 
 * @returns 
 */
const loopRouteItem = (routes: MenuItem[]): RouteItem[] => {
  const normalizeComponentPath = (path?: string, component?: string): string => {
    if (component) return component.replace(/^\//, '').replace(/\.(tsx|jsx)$/i, '');
    if (!path) return '';
    return path.replace(/^\//, '').replace(/\.(tsx|jsx)$/i, '');
  };

  const processRoute = (route: MenuItem): RouteItem | null => {
    if (route.is_source === true) return null;

    const routeWithoutCustomProps = removeCustomProps(route);

    const children = route.children?.length 
      ? loopRouteItem(route.children).filter(child => child !== null) as RouteItem[]
      : undefined;

    if (children && children.length > 0) {
      const firstChild = children[0];
      return {
        ...routeWithoutCustomProps,
        element: undefined,
        children: [
          { path: '', element: <Navigate to={firstChild.path as any} replace /> },
          ...children
        ],
        routes: children
      };
    }

    const componentPath = normalizeComponentPath(
      route.path, 
      (route as any).component
    );
    
    const Component = componentPath 
      ? React.lazy(() => import(`@/pages/${componentPath}`).catch(() => import('@/pages/404')))
      : null;

    return {
      ...routeWithoutCustomProps,
      element: Component ? (
        <React.Suspense fallback={<Loading />}>
          <Component />
        </React.Suspense>
      ) : undefined,
      children,
      routes: children
    };
  };

  return routes.map(processRoute).filter(route => route !== null) as RouteItem[];
};

/**
 * filterSourceRoutes 过滤删除掉is_source 为true 的 因为动态路由配置在本地的 无需动态导入
 * @returns 
 */
const dealDynamicRoutes=(data: MenuItem[])=>{
  const routesForRegistration = filterSourceRoutes(data);
  return loopRouteItem(routesForRegistration);
}

export async function patchClientRoutes({ routes }: any) {
  // 确保数据已加载
  if (!appState.isLoaded) {
    await loadUserAndMenuState();
  }

  try {
    const routerIndex = routes.findIndex((item: any) => item.path === '/');
    if (routerIndex === -1) return;
    
    const localRoutes = routes[routerIndex]?.children || [];
    const dynamicRoutes = appState.dynamicRoutes || [];
    const mergedRoutes = mergeRoutes(localRoutes, dynamicRoutes);
    
    routes[routerIndex] = {
      ...routes[routerIndex],
      children: mergedRoutes,
      routes: mergedRoutes
    };
  } catch (error) {
    console.error('路由合并失败:', error);
  }
}

// 退出登录函数 - 暴露给全局使用

const logout = () => {
  // 1. 清除本地 token
  localStorage.removeItem("token");
  
  // 2. 重置全局状态
  appState = {
    currentUser: null,
    menuList: [],
    dynamicRoutes:[],
    isLoaded: false,
    token: ''
  };
  
  // 3. 跳转到登录页
  history.replace("/login");
  
  // 4. 强制刷新页面以清除所有状态（可选但推荐）
  window.location.reload();
};

export async function getInitialState() {
  // 确保数据已加载
  if (!appState.isLoaded) {
    await loadUserAndMenuState();
  }
  
  return { 
    currentUser: appState.currentUser || {}, 
    menuList: appState.menuList || [],
    logout:logout
  };
}



export async function onRouteChange({ location }: { location: Location }) {
  const { pathname } = location;
  // 直接从全局状态获取用户数据，避免再次加载
  const currentUser = appState.currentUser;
  if (!currentUser || Object.keys(currentUser).length === 0) {
    if (pathname !== '/login') {
      history.replace('/login');
    }
  } else if (pathname === '/login') {
    history.replace('/');
  }
}

export function render(oldRender: () => void) {
  // 在应用启动时加载数据
  loadUserAndMenuState().then(oldRender).catch(err => {
    console.error('加载应用状态失败:', err);
    oldRender();
  });
}